package example.controller;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class UrlImage extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		URLFetchService fetchService =
            URLFetchServiceFactory.getURLFetchService();
		URL url = new URL("http://media.y8.com/system/contents/16776/original/Shoot_m.swf");
		// Fetch the image at the location given by the url query string parameter
		FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
		fetchOptions.setDeadline((double)30*60);
		HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
        HTTPResponse fetchResponse = fetchService.fetch(request);
        
        String fetchResponseContentType = null;
        for (HTTPHeader header : fetchResponse.getHeaders()) {
            // For each request header, check whether the name equals
            // "Content-Type"; if so, store the value of this header
            // in a member variable
            if (header.getName().equalsIgnoreCase("content-type")) {
                fetchResponseContentType = header.getValue();
                break;
            }
        }
        if (fetchResponseContentType != null) {
        	byte[] img = (byte[]) fetchResponse.getContent();
        	System.out.print(fetchResponseContentType);
        	resp.setContentType(fetchResponseContentType);
        	resp.getOutputStream().write(img);
        	
        }
	}
}
